import {Component, ViewChild} from '@angular/core';

import {Storage} from '@ionic/storage';

import {Events, ModalController, NavController, ActionSheetController, Content} from 'ionic-angular';

import {Config} from '../../../../providers/config';

import {Common} from '../../../../providers/common';

import _ from 'lodash';
import {MarketingWeeklyListService} from "./list.service";
import {MarketingWeeklyQueryPage} from "../query/query.component";
import {MarketingWeeklyDetailPage} from "../detail/detail.component";
import {MarketingWeeklyEditPage} from "../edit/edit.component";
import {ContactChoosePage} from "../../../contact/choose/choose.component";

@Component({
  selector: 'page-marketing-weekly-list',
  templateUrl: './list.html',
  providers: [MarketingWeeklyListService]
})
export class MarketingWeeklyListPage {
  moa_page_name: any = "page-marketing-weekly-list";
  moa_page_explain: any = "工作周报";

  @ViewChild(Content) content: Content;

  // 列表数据
  listData: any = [];
  //显示标题
  title = '';

  _ = _;
  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  keyWord = null;
  //
  queryCondition = null;

  defaultEmpByTree = [];

  constructor(public modalCtrl: ModalController,
              public navCtrl: NavController,
              public events: Events,
              public config: Config,
              public storage: Storage,
              public common: Common,
              public listService: MarketingWeeklyListService,
              public actionSheetCtrl: ActionSheetController) {

    this.storage.set("queryText", "");
    this.events.unsubscribe('weekly-list:update');
    // 监听是否有更新邮件操作
    this.events.subscribe('weekly-list:update', (item) => {
      console.info('---- list--weekly-list:update------');
      var index = _.findIndex(this.listData, {
        '0': item[0]
      });
      if (index >= 0) {
        this.listData[index] = item;
      } else {
        this.listData.splice(0, 0, item);
      }
    });

    this.storage.remove("advancedQueryCondition");

    this.initQueryCondition();

    // 初始化数据
    this.loadListData(this.pageIndex, null, null);

  }


  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(page, infiniteScroll, refresher) {
    this.listService.getListData(page, this.queryCondition).subscribe(data => {
      console.log(data);
      if (data) {
        var dataList = [];
        _.forEach(data, function (i) {
          let d = i.split("|");
          dataList.push(d);
        });

        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData = _.concat(this.listData, dataList);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;

        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      } else {
        if (this.pageIndex == 1) {
          this.listData = [];
        }
        // this.listData = [];
        this.isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  }

  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    console.info(item);
    this.navCtrl.push(MarketingWeeklyDetailPage, {
      "detail": item
    });
  }

  /**
   * [goEditPage 跳转新增页面]
   * @param {[type]} item [参数]
   */
  goEditPage() {
    this.navCtrl.push(MarketingWeeklyEditPage, {});
  }

  ionViewDidLoad() {

  }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }

  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    this.loadListData(this.pageIndex, null, refresher);
  }


  //邮件搜索
  search() {
    let that = this;
    //console.log("##search 关键字：" + this.keyWord);
    this.content.scrollTo(0, 0, 100);
    this.initQueryCondition();
    this.pageIndex = 1;
    this.queryCondition.emp = this.keyWord;
    if (this.keyWord) {
      this.common.getContactNameByJianPin(this.keyWord, 0).then((dataList: string[]) => {
        that.listService.getAllAuthority().subscribe(authList => {
          console.log(dataList);
          let empString = "";
          _.forEach(dataList, d => {
            let temp = _.result(_.find(authList, {"usr_nm": d}), "usr_nm");
            if (temp) {
              if (empString == "") {
                empString = "'" + _.toString(temp) + "'";
              } else {
                empString += ",'" + temp + "'";
              }
            }
          });
          if (empString == "") {
            empString = "''";
          }
          that.queryCondition.emp = empString;
          that.loadListData(this.pageIndex, null, null);
        });
      });
    } else {
      this.queryCondition.emp = "'ALL'";
      this.loadListData(this.pageIndex, null, null);
    }
  }

  showAdvancedQueryModal() {
    let that = this;
    console.log("打开Modal");
    let queryModal = this.modalCtrl.create(MarketingWeeklyQueryPage, {});
    queryModal.onWillDismiss(data => {
      if (data && data != "close") {
        this.storage.get("advancedQueryCondition")
          .then(data => {
            if (data != null) {
              this.queryCondition = data;
              this.queryCondition.startdate.replace("-", "");
              this.queryCondition.enddate.replace("-", "");
              this.keyWord = "";
              this.pageIndex = 1;

              if (this.queryCondition.emp == '') {
                that.queryCondition.emp = "'ALL'";
                this.loadListData(this.pageIndex, null, null);
              } else {
                let dataList = this.queryCondition.emp.split(",");
                that.listService.getAllAuthority().subscribe(authList => {
                  console.log(dataList);
                  let empString = "";
                  _.forEach(dataList, d => {
                    let temp = _.result(_.find(authList, {"usr_nm": d}), "usr_nm");
                    if (temp) {
                      if (empString == "") {
                        empString = "'" + _.toString(temp) + "'";
                      } else {
                        empString += ",'" + temp + "'";
                      }
                    }
                  });
                  if (empString == "") {
                    empString = "''";
                  }
                  that.queryCondition.emp = empString;
                  that.loadListData(this.pageIndex, null, null);
                });
              }
            }
          });
      }
    });
    queryModal.present();
  }

  initQueryCondition() {
    this.queryCondition = {
      "emp": "'ALL'",
      "startdate": (this.common.getDate(-30)).replace("-", ""),
      "enddate": (this.common.getNowFormatDate()).replace("-", "")
    }
  }

  chooseListType() {
    let bottons = [{
      text: '新增工作周报',
      role: '',
      handler: () => {
        this.goEditPage();
      }
    }, {
      text: '高级查询',
      role: '',
      handler: () => {
        this.showAdvancedQueryModal();
      }
    }, {
      text: '取消',
      role: 'cancel',
      handler: () => {

      }
    }];

    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  };

  selectEmp() {
    console.log("##authorization.detail.chooseEmpnames 选择外出人员");
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaultEmpByTree,
      isSelectUser: true,
      isSelectOne: true,
      isSaveQueryText: true
    });

    modal.present();
    modal.onWillDismiss((data: any[]) => {
      console.info(data);
      if (data && data.length > 0) {
        that.defaultEmpByTree = data;
        that.queryCondition.emp = _.toString(_.map(data, "name"));
        that.keyWord = that.queryCondition.emp;
        that.pageIndex = 1;
        that.loadListData(that.pageIndex, null, null);
      } else {
        if (typeof data != "undefined") {
          this.storage.get("queryText").then(q => {
            that.keyWord = q;
            that.queryCondition.emp = that.keyWord;
            that.pageIndex = 1;
            that.loadListData(that.pageIndex, null, null);
          });
        }
      }
    });
  }

}


